package com.rightrule.rule.script;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyCodeSource;
import groovy.lang.GroovyShell;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

@Component
@Slf4j
@Data
public class ScriptFactory {

    /**
     * 获取编译后的脚本执行类
     *
     * @param scriptContent
     * @param scriptName
     * @param fieldLogic
     * @return
     */
    public static Class getScriptClass(String scriptContent, String scriptName, String fieldLogic) {
        String importClass = "";
        if (!StringUtils.isEmpty(fieldLogic)) {
            JSONObject jsonFieldLogic = JSONObject.parseObject(fieldLogic);
            if (jsonFieldLogic.containsKey("importClass")) {
                importClass = jsonFieldLogic.getString("importClass");
            }
        }

        String script = getScript(scriptContent, importClass);
        long start = System.currentTimeMillis();
        // 获取当前线程对应的类加载器
        GroovyClassLoader classLoader = new GroovyClassLoader(Thread.currentThread().getContextClassLoader());
        Class aClass = classLoader.parseClass(new GroovyCodeSource(script, scriptName, GroovyShell.DEFAULT_CODE_BASE));
        long end = System.currentTimeMillis();

        log.info("ScriptFactory classLoader parseClass time :{} ms", end - start);
        return aClass;
    }

    /**
     * 组装脚本，替换标记位
     *
     * @param logic
     * @param importString
     * @return
     */
    public static String getScript(String logic, String importString) {
        String replacedLogic = replaceMarks(logic);
        // todo 逻辑待实现
//        String script = BaseScript.import_string;
        String script = "";

        return script;
    }


    /**
     * 替换标记位
     *
     * @param logic
     * @return
     */
    public static String replaceMarks(String logic) {
        // todo  逻辑待实现
//        List<String> candidateMethod  =StringMatchUtil.extractBetweenSting(logic,"0","//");
        List<String> candidateMethod = Lists.newArrayList();

        if (CollectionUtils.isEmpty(candidateMethod)) {
            return logic;
        }
        // todo 逻辑待实现
        else {
            String runnableLogic = "";
            return runnableLogic;
        }
    }
}
